package com.hty.PowerChat;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import pclientbackend.ChatClient;
import pclientbackend.Pclientbackend;

public class ChatActivity extends AppCompatActivity {

    Button button_send;
    TextView textView_title_chat;
    ImageButton imageButton_chat_back, imageButton_contact_info, imageButton_addfile;
    EditText editText_message;
    ListView listView_chat;
    //List<Map<String,Object>> list_chat_items = new ArrayList<>();
    ArrayList<HashMap<String,Object>> list_chat = new ArrayList<>();
    SimpleAdapter adapter_chat;
    //ChatAdapter adapter_chat;
    final int ME = 0, OTHER = 1;
    int[] layout_chat_item = { R.layout.list_chat_item_left, R.layout.list_chat_item_right };
    InputMethodManager IMM;
    String cname, csex="女", cage, cdesc, cid, uid;
    ChatClient chatClient;
    SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    boolean exitRefreshMessageThread = false;
    int position = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //使用自定义布局
        actionBar.setCustomView(R.layout.actionbar_chat);
        textView_title_chat = findViewById(R.id.textView_title_chat);
        imageButton_chat_back = findViewById(R.id.imageButton_chat_back);
        imageButton_contact_info = findViewById(R.id.imageButton_contact_info);
        imageButton_addfile = findViewById(R.id.imageButton_addfile);
        imageButton_chat_back.setOnClickListener(new ClickListener());
        imageButton_contact_info.setOnClickListener(new ClickListener());
        imageButton_addfile.setOnClickListener(new ClickListener());

        IMM = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        SharedPreferences SP = getSharedPreferences("userData", MODE_PRIVATE);  // (文件名，操作模式)
        uid = SP.getString("uid", "");

        Intent intent = getIntent();
        HashMap map = (HashMap) intent.getSerializableExtra("contact");
        cname = map.get("name").toString();
        textView_title_chat.setText(cname);
        cid = map.get("id").toString();
        long sex = (long) map.get("sex");
        if(sex == 1){
            csex = "男";
        }
        cage = map.get("age").toString();
        cdesc = map.get("desc").toString();

        button_send = findViewById(R.id.button_send);
        button_send.setOnClickListener(new ClickListener());
        editText_message = findViewById(R.id.editText_message);

        adapter_chat = new SimpleAdapter(this, list_chat, R.layout.list_chat_item_left, new String[]{ "index", "avatar", "time", "message",  }, new int[]{ R.id.textView_index, R.id.imageView_avatar_other, R.id.textView_time, R.id.textView_message_other });
        adapter_chat.setViewBinder(new SimpleAdapter.ViewBinder(){
            public boolean setViewValue(View view, Object data, String textRepresentation){
                if (view.getId() == R.id.textView_message_other) {
                    String message = (String)data;
                    ((TextView)view).setText(message);
                    if (message.startsWith("TEXTSending:")) {
                        ((TextView)view).setText("发送文件：" + message.substring(12));
                    } else if (message.equals("F OK\n")) {
                        ((TextView)view).setText("文件已接收");
                    } else if (message.startsWith("TEXT")) {
                        ((TextView)view).setText(message.substring(4));
                    } else if (message.startsWith("JSON{")) {
                        ((TextView)view).setText(message);
                        String json = message.substring(4);
                        try {
                            JSONObject JO = new JSONObject(json);
                            String filepath = JO.getString("Name");
                            String mime = URLConnection.getFileNameMap().getContentTypeFor(filepath);
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", filepath + ", " + mime);
                            if (mime != null) {
                                if (mime.startsWith("image/")) {
                                    //((TextView)view).setTextColor(Color.argb(0,0,0,0)); //文字透明
                                    File file = new File(filepath);
                                    if (file.exists()) {
                                        view.setBackground(Drawable.createFromPath(filepath));
                                    } else {
                                        view.setBackgroundResource(android.R.drawable.ic_menu_report_image);
                                    }
                                    return true;
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", "JSON解析错误：" + json);
                        }
                    }
                    view.setBackgroundResource(R.mipmap.message_background);
                    return true;
                }
                return false;
            }
        });
        //String[] from = { "avatar", "message" };
        //int[] to = { R.id.imageView_avatar_me, R.id.textView_message_me, R.id.imageView_avatar_other, R.id.textView_message_other };
        //adapter_chat = new ChatAdapter(this, list_chat, layout_chat_item, from, to);
        listView_chat = findViewById(R.id.listView_chat);
        listView_chat.setAdapter(adapter_chat);
        listView_chat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int position, long id) {
                String message = ((TextView) view.findViewById(R.id.textView_message_other)).getText().toString();
                if (message.startsWith("JSON{")) {
                    String json = message.substring(4);
                    try {
                        JSONObject JO = new JSONObject(json);
                        String filepath = JO.getString("Name");
                        File file = new File(filepath);
                        if (file.exists()) {
                            String mime = URLConnection.getFileNameMap().getContentTypeFor(filepath);
                            if(mime != null){
                                Log.e(Thread.currentThread().getStackTrace()[2] + "MIME", mime);
                                //Toast.makeText(getApplicationContext(), mime, Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_VIEW);
                                intent.setDataAndType(Uri.fromFile(new File(filepath)), mime);
                                startActivity(intent);
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", "JSON解析错误：" + json);
                    }
                } else if (message.contains("http://") || message.contains("https://")) {
                    String url = message.substring(message.indexOf("http"));
                    //Log.e(Thread.currentThread().getStackTrace()[2] + "", url);
                    Intent intent = new Intent(ChatActivity.this, BrowserActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            }
        });

        listView_chat.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
                String title = ((TextView) info.targetView.findViewById(R.id.textView_message_other)).getText().toString();
                menu.setHeaderTitle(title);
                menu.add(0, 0, 0, "复制");
                menu.add(0, 1, 1, "删除");
            }
        });


        editText_message.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (TextUtils.isEmpty(charSequence.toString().trim())) {
                    button_send.setBackgroundColor(Color.parseColor("#CCCCCC"));
                    button_send.setEnabled(false);
                } else {
                    button_send.setBackgroundColor(Color.parseColor("#169FE6"));
                    button_send.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        listView_chat.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                IMM.hideSoftInputFromWindow(ChatActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                return false;
            }
        });

        String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "PowerChat";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String json = "{\"Host\":\"148.70.58.15:7889\"}";
        chatClient = Pclientbackend.getChatClient(path, json);
    }

    class ClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.imageButton_chat_back:
                    exitRefreshMessageThread = true;
                    finish();
                    break;
                case R.id.imageButton_contact_info:
                    String s = "Id：\t" + cid + "\n用户名：\t" + cname + "\n" + "性别：\t" + csex + "\n" + "年龄：\t" + cage + "\n签名：\t" + cdesc;
                    AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
                    builder.setIcon(R.mipmap.avatar);
                    builder.setTitle("用户");
                    builder.setMessage(s);
                    builder.setPositiveButton("空间", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            chatClient.setServeId(Long.parseLong(cid));
                            String url = chatClient.getUrl();
                            Log.e(Thread.currentThread().getStackTrace()[2] + "", url);
                            Intent intent = new Intent(ChatActivity.this, BrowserActivity.class);
                            intent.putExtra("url", url);
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                    break;
                case R.id.button_send:
                    String message = editText_message.getText().toString();
                    chatClient.chatTo(Long.parseLong(cid), message);
                    DBHelper DBH = new DBHelper(getApplicationContext());   //报错
                    //DBHelper DBH = DBHelper.getInstance(getApplicationContext()); //偶尔崩溃
                    ContentValues values = new ContentValues();
                    values.put("message", message);
                    values.put("mfrom", uid);
                    values.put("mto", cid);
                    Date time = new Date();
                    values.put("time", timeformat.format(time));
                    DBH.insert("chat" + uid, values);
                    editText_message.setText("");
                    break;
                case R.id.imageButton_addfile:
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    //intent.setType(“image/*”);    //图片
                    //intent.setType(“audio/*”);    //音频
                    //intent.setType(“video/*”);    //视频
                    //intent.setType(“video/*;image/*”);    //同时选择视频和图片
                    intent.setType("*/*");  //无类型限制
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, 1);
                    break;
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                adapter_chat.notifyDataSetChanged();
                listView_chat.setSelection(list_chat.size()-1);
            }else if (msg.what == -1) {
                adapter_chat.notifyDataSetChanged();
                listView_chat.setSelection(position);
            }
        }
    };

    void getMessage(int n) {
        DBHelper DBH = new DBHelper(getApplicationContext());   //报错
        //DBHelper DBH = DBHelper.getInstance(getApplicationContext());//崩溃
        Cursor cursor = DBH.query("chat" + uid, cid, "");
        if(cursor.getCount() > n) {
            list_chat.clear();
            while (cursor.moveToNext()) {
                int index = cursor.getInt(cursor.getColumnIndex("_id"));
                String message = cursor.getString(cursor.getColumnIndex("message"));
                String from = cursor.getString(cursor.getColumnIndex("mfrom"));
                String to = cursor.getString(cursor.getColumnIndex("mto"));
                String time = cursor.getString(cursor.getColumnIndex("time"));
                //Log.e(Thread.currentThread().getStackTrace()[2] + "", from + ", " + to + ", " + cid);
                HashMap<String, Object> listItem = new HashMap<>();
                listItem.put("index", index);
                if(from.equals(cid)){
                    listItem.put("avatar", R.mipmap.avatar);
                }else{
                    listItem.put("avatar", R.mipmap.logo);
                }
                listItem.put("message", message);
                listItem.put("time", time);
                list_chat.add(listItem);
            }
            cursor.close();
            Message msg = new Message();
            if(n == -1){
                msg.what = -1;
            }else {
                msg.what = 0;
            }
            handler.sendMessage(msg);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitRefreshMessageThread = true;
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onPause() {
        super.onPause();
        exitRefreshMessageThread = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        exitRefreshMessageThread = false;
        RefreshMessageThread refreshMessageThread = new RefreshMessageThread();
        refreshMessageThread.start();
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case 0:
                ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                String message = ((TextView) menuInfo.targetView.findViewById(R.id.textView_message_other)).getText().toString();
                cm.setPrimaryClip(ClipData.newPlainText("message", message));
                break;
            case 1:
                int id = Integer.parseInt(((TextView) menuInfo.targetView.findViewById(R.id.textView_index)).getText().toString());
                DBHelper DBH = new DBHelper(getApplicationContext());   //报错
                //DBHelper DBH = DBHelper.getInstance(getApplicationContext());//崩溃
                if (DBH.del("chat" + uid, id) > 0) {
                    position = listView_chat.getFirstVisiblePosition();
                    getMessage(-1);
                }
                DBH.close();
                break;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Log.e(Thread.currentThread().getStackTrace()[2] + "", uri.toString());
            String filepath = getPathFromURI(uri);
            Log.e(Thread.currentThread().getStackTrace()[2] + "", filepath);
            long r = chatClient.sendFile(Long.parseLong(cid), filepath);
            DBHelper DBH = new DBHelper(getApplicationContext());   //报错
            //DBHelper DBH = DBHelper.getInstance(getApplicationContext());//崩溃
            ContentValues values = new ContentValues();
            String message = "JSON{\"Name\":\"" + filepath + "\",\"response\":"+ r + "}";
            values.put("message", message);
            values.put("mfrom", uid);
            values.put("mto", cid);
            Date time = new Date();
            values.put("time", timeformat.format(time));
            DBH.insert("chat" + uid, values);
            DBH.close();
        }
    }

    String getPathFromURI(Uri uri) {
        String res = null;
        String[] proj = { "_data" };
        Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
        if(null != cursor && cursor.moveToFirst()){;
            int column_index = cursor.getColumnIndexOrThrow("_data");
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    Drawable drawableFitWidth(String filepath, int viewWidth){
        Drawable drawable = null;
        File file = new File(filepath);
        Bitmap bitmap;
        if (file.exists()) {
            bitmap = BitmapFactory.decodeFile(filepath);
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_report_image);
        }
        Matrix matrix = new Matrix();
        float ratio = (float) viewWidth / bitmap.getWidth();
        //Log.e(Thread.currentThread().getStackTrace()[2] + "", ratio + "");
        matrix.postScale(ratio, ratio);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        drawable = new BitmapDrawable(getResources(), bitmap);
        return drawable;
    }

    class RefreshMessageThread extends Thread{
        public void run(){
            while(!exitRefreshMessageThread){
                getMessage(list_chat.size());
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}